import {Directive, ElementRef, HostListener, Inject, Input, Renderer2} from '@angular/core';
import {DOCUMENT} from '@angular/common';

@Directive({
    selector: '[appHideOnClickOutside]'
})
export class HideOnClickOutsideDirective {
    constructor(private element: ElementRef,
                private renderer: Renderer2,
                @Inject(DOCUMENT) private document: Document) {
    }

    @Input()
    clickOutsideRemoveClass: string;

    @HostListener('window:click', ['$event'])
    onWindowClick(event) {
        const target = event.target;
        if (this.isOutside(target, this.element.nativeElement)) {
            // 点中外面
            if (this.clickOutsideRemoveClass) {
                this.renderer.removeClass(this.element.nativeElement, this.clickOutsideRemoveClass);
            } else {
                this.renderer.addClass(this.element.nativeElement, 'hide');
            }
        }
    }

    private isOutside(target: any, element: any): boolean {
        if (!target || target instanceof Document) {
            return true;
        }
        if (target === element) {
            return false;
        }
        if (target.classList.contains('no-hide-on-click')) {
            return false;
        }
        return this.isOutside(target.parentNode, element);
    }
}
